<script setup lang="ts">
import axios, { AxiosError } from "axios"
import { ref, onMounted } from "vue"
import { ElMessage } from "element-plus"

const account = ref<string>("")
const password = ref<string>("")
const userInfo = ref<UserInfo | null>(null)
const resourceList = ref<Resource[]>([])
const loading = ref<boolean>(false)

const api = axios.create({
  baseURL: "/api",
  timeout: 10000
})

api.interceptors.request.use(config => {
  const token = sessionStorage.getItem("token")
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

api.interceptors.response.use(
    res => {
      if (res.data.code !== 200) {
        return Promise.reject(new Error(res.data.message || "业务处理失败"))
      }
      return res
    },
    (err: AxiosError<ApiResponse<any>>) => {
      if (err.response?.status === 401) {
        ElMessage.error("登录过期，请重新登录")
        sessionStorage.clear()
      } else {
        ElMessage.error(err.response?.data.message || "网络请求失败")
      }
      return Promise.reject(err)
    }
)

// 4. 登录注册函数（优化错误处理）
async function login(): Promise<void> {
  if (!account.value || !password.value) {
    ElMessage.warning("请输入账号和密码")
    return
  }

  try {
    loading.value = true
    const res = await api.post<ApiResponse<{ token: string; userId: number }>>("/auth/login", {
      account: account.value,
      password: password.value
    })

    const { token, userId } = res.data.data
    sessionStorage.setItem("token", token)
    sessionStorage.setItem("userId", userId.toString())
    ElMessage.success("登录成功")
    await getUserinfo()
  } catch (err) {
    console.error("登录失败:", err)
  } finally {
    loading.value = false
  }
}

async function register(): Promise<void> {
  if (!account.value || !password.value) {
    ElMessage.warning("请输入账号和密码")
    return
  }

  try {
    loading.value = true
    const res = await api.post<ApiResponse<any>>("/auth/register", {
      account: account.value,
      password: password.value
    })
    ElMessage.success("注册成功")
    console.log(res.data)
  } catch (err) {
    console.error("注册失败:", err)
  } finally {
    loading.value = false
  }
}

async function getUserinfo(): Promise<void> {
  const token = sessionStorage.getItem("token")
  const userId = sessionStorage.getItem("userId")

  console.log("Token:", token, "UserId:", userId)

  if (!token || !userId) {
    ElMessage.warning("请先登录")
    return
  }

  try {
    const res = await api.get<ApiResponse<UserInfo>>("/user/getUserInfo", {
      params: { userId: Number(userId) }
    })
    userInfo.value = res.data.data
    ElMessage.success("获取用户信息成功")
    console.log("用户信息:", JSON.stringify(res.data.data, null, 2))
  } catch (err) {
    console.error("获取用户信息失败:", err)
  }
}

async function getResourceList(): Promise<void> {
  const token = sessionStorage.getItem("token")
  const userId = sessionStorage.getItem("userId")

  if (!token || !userId) {
    ElMessage.warning("请先登录")
    return
  }

  try {
    loading.value = true

    // 明确指定返回类型结构
    const res = await api.get<ApiResponse<{
      records: Resource[]
      total: number
      pages: number
      current: number
      size: number
    }>>("/resource/getResourceList", {
      params: { userId: Number(userId) }
    })

    const data = res.data.data
    resourceList.value = data.records || []

    console.log("资源列表加载成功:", resourceList.value)
    ElMessage.success(`成功获取 ${resourceList.value.length} 条资源`)

  } catch (err) {
    console.error("获取资源列表失败:", err)
    resourceList.value = []
    ElMessage.error("获取资源列表失败")
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const token = sessionStorage.getItem("token")
  if (token) {
    getUserinfo()
    getResourceList()
  }
})
</script>

<template>
  <div class="container">
    <div class="auth-section">
      <input v-model="account" placeholder="请输入用户名或手机号" type="text" />
      <input v-model="password" placeholder="请输入密码" type="password" />

      <div class="button-group">
        <button @click="login" :disabled="loading">登录</button>
        <button @click="register" :disabled="loading">注册</button>
      </div>
    </div>

    <div v-if="userInfo" class="user-info">
      <h3>用户信息</h3>
      <p>用户名：{{ userInfo.username }}</p>
      <p>用户ID：{{ userInfo.id }}</p>
      <p>手机号：{{ userInfo.phone || '未绑定' }}</p>
      <p>位置：{{ userInfo.location || '未知' }}</p>
      <p>是否为会员：{{ userInfo.isVip === 1 ? '是' : '否' }}</p>
    </div>

    <div class="resource-section">
      <button @click="getResourceList" :disabled="loading">刷新资源列表</button>

      <div v-if="loading" class="loading">加载中...</div>

      <div v-if="resourceList.length > 0" class="resource-list">
        <ul>
          <li v-for="resource in resourceList" :key="resource.id" class="resource-item">
            <h4>{{ resource.title }}</h4>
            <p>{{ resource.introduction }}</p>
            <div class="meta">
              <span>发布者：{{ resource.PublishUsername || '匿名' }}</span>
              <span>标签：{{ resource.resourceTag }}</span>
              <span>位置：{{ resource.Location }}</span>
              <span :class="{ vip: resource.isVipOnly }">
                {{ resource.isVipOnly ? 'VIP专享' : '免费' }}
              </span>
            </div>
            <a :href="resource.ResourceURL" target="_blank">查看资源</a>
            <small>发布时间：{{ resource.createTime }}</small>
          </li>
        </ul>
      </div>

      <div v-else-if="!loading" class="empty">
        暂无资源数据
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.auth-section {
  margin-bottom: 30px;
}

input {
  display: block;
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.button-group {
  display: flex;
  gap: 10px;
}

button {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.user-info {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.resource-list ul {
  list-style: none;
  padding: 0;
}

.resource-item {
  border: 1px solid #ebeef5;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 6px;
  background-color: #fff;
}

.meta span {
  margin-right: 15px;
  font-size: 14px;
  color: #666;
}

.meta .vip {
  color: #e6a23c;
  font-weight: bold;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #409eff;
}

.empty {
  text-align: center;
  padding: 40px;
  color: #909399;
}
</style>